package co.edu.usbcali.unidades.dataaccess.dao;

import co.edu.usbcali.unidades.dataaccess.sessionFactory.HibernateSessionFactory;
import co.edu.usbcali.unidades.modelo.DtoCorrespondencia;
import co.edu.usbcali.unidades.modelo.Estado;
import co.edu.usbcali.unidades.modelo.Factura;
import co.edu.usbcali.unidades.modelo.Persona;
import co.edu.usbcali.unidades.modelo.TipoCorrespondencia;
import co.edu.usbcali.unidades.modelo.dto.FacturasPorPagarDTO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;

import org.hibernate.criterion.Example;

import java.math.BigDecimal;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * A data access object (DAO) providing persistence and search support for
 * Factura entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 *
 *
 * @author Zathura Code Generator http://code.google.com/p/zathura
 *
 */
public class FacturaDAO implements IFacturaDAO {
    private static final Log log = LogFactory.getLog(FacturaDAO.class);

    // property constants
    //public static final String  FACCODIGO = "facCodigo";
    public static final String FACCODIGO = "facCodigo";

    //public static final Date  FACFECHA = "facFecha";
    public static final String FACFECHA = "facFecha";

    private Session getSession() {
        return HibernateSessionFactory.getSession();
    }

    /**
    *
    * @param Instance
    *            Factura Instance to persist
    * @throws RuntimeException
    *             when the operation fails
    */
    public void save(Factura instance) {
        log.debug("saving Factura instance");

        try {
            getSession().save(instance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    /**
    * @param Instance
    *            Factura Instance to delete
    * @throws RuntimeException
    *             when the operation fails
    */
    public void delete(Factura instance) {
        log.debug("deleting Factura instance");

        try {
            getSession().delete(instance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    /**
    *
    * @param Instance
    *            Factura Instance to update
    * @throws RuntimeException
    *             when the operation fails
    */
    public void update(Factura instance) {
        log.debug("updating Factura instance");

        try {
            getSession().update(instance);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }

    public Factura findById(String id) {
        log.debug("finding Factura instance with id: " + id);

        try {
            Factura instance = (Factura) getSession().get(Factura.class, id);

            return instance;
        } catch (RuntimeException re) {
            log.error("finding Factura failed", re);
            throw re;
        }
    }

    public List<Factura> findByExample(Factura instance) {
        log.debug("finding Factura instance by example");

        try {
            List results = getSession().createCriteria("Factura")
                               .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: " +
                results.size());

            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    /**
    * Find all  Factura entities with a specific property value.
    *
    * @param value
    *            the property value to match
    * @param propertyName
    *            the property to search in the instance
    * @return List< Factura> found by query
        */
    public List<Factura> findByProperty(String propertyName, Object value) {
        log.debug("finding Factura instance with property: " + propertyName +
            ", value: " + value);

        try {
            String queryString = "from Factura as model where model." +
                propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List<Factura> findByFacCodigo(Object facCodigo) {
        return findByProperty(FACCODIGO, facCodigo);
    }

    public List<Factura> findByFacFecha(Object facFecha) {
        return findByProperty(FACFECHA, facFecha);
    }

    /**
    * Find all Factura entities.
    *
    * @return List<Factura> all Factura instances
    */
    public List<Factura> findAll() {
        log.debug("finding all Factura instances");

        try {
            String queryString = "from Factura";
            Query queryObject = getSession().createQuery(queryString);

            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public List<Factura> findByCriteria(String whereCondition) {
        log.debug("finding Factura " + whereCondition);

        try {
            String where = ((whereCondition == null) ||
                (whereCondition.length() == 0)) ? "" : ("where " +
                whereCondition);
            final String queryString = "select model from Factura model " +
                where;
            Query query = getSession().createQuery(queryString);
            List<Factura> entitiesList = query.list();

            return entitiesList;
        } catch (RuntimeException re) {
            log.error("find By Criteria in Factura failed", re);
            throw re;
        }
    }

    public List<Factura> findPageFactura(String sortColumnName,
        boolean sortAscending, int startRow, int maxResults) {
        log.debug("finding Factura findPageFactura");

        if ((sortColumnName != null) && (sortColumnName.length() > 0)) {
            try {
                String queryString = "select model from Factura model order by model." +
                    sortColumnName + " " + (sortAscending ? "asc" : "desc");

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        } else {
            try {
                String queryString = "select model from Factura model";

                return getSession().createQuery(queryString)
                           .setFirstResult(startRow).setMaxResults(maxResults)
                           .list();
            } catch (RuntimeException re) {
                throw re;
            }
        }
    }

    public Long findTotalNumberFactura() {
        log.debug("finding Factura count");

        try {
            String queryString = "select count(*) from Factura model";
            Query queryObject = getSession().createQuery(queryString);

            return (Long) queryObject.list().get(0);
        } catch (RuntimeException re) {
            throw re;
        }
    }

	public Date ultimaFechaFactura() {
		try {
			List<Date> fechas = null;
            String queryString = "select max(f.facFecha) from Factura f";
            Query queryObject = getSession().createQuery(queryString);
            fechas = queryObject.list();
            return fechas.get(0);
        } catch (RuntimeException re) {
            throw re;
        }
	}

	public List<Factura> darFacturas() {
		try {
			Date ultimaFecha = ultimaFechaFactura();
			System.out.println(ultimaFecha);
			SimpleDateFormat c = new SimpleDateFormat("dd/MM/yyyy");
			String s = c.format(ultimaFecha);
			
			String queryString = "select f from Factura f where f.facFecha = (select max(facFecha) from Factura)";
            Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		 } catch (RuntimeException re) {
	            throw re;
	     }
	}
	
	public List<FacturasPorPagarDTO> getFacturasActivasPropietario(String codPro) {
		try {
			
			String queryString = "select f from Factura f where f.propietarioInmueble.priCodigo=:codigo and f.estado.estCodigo='1'";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter("codigo", codPro);
            
            List <Factura> dt = queryObject.list();
            
            List<FacturasPorPagarDTO> dtoEncontrados = new ArrayList<FacturasPorPagarDTO>();
            
            for(int i =0; i < dt.size(); i++){			
    			FacturasPorPagarDTO datosDt = new FacturasPorPagarDTO();
    			
    			datosDt.setFacCodigo(dt.get(i).getFacCodigo());
    			datosDt.setEstado(dt.get(i).getEstado());
    			datosDt.setFacFecha(dt.get(i).getFacFecha());
    			
    			Date fechaL = dt.get(i).getFacFecha();
    			Calendar calendar = Calendar.getInstance();                
                //Posiciono la fecha del calendario a una fecha especifica
                calendar.setTime(fechaL);
                calendar.add(Calendar.DATE, 15);
                fechaL = calendar.getTime();
                
    			datosDt.setFacFechaLimite(fechaL);
    			datosDt.setValor(calculaTotal(dt.get(i).getFacCodigo()));
    			dtoEncontrados.add(datosDt);
    			
    		}
			return dtoEncontrados;
		 } catch (RuntimeException re) {
	            throw re;
	     }
	}
	
	//Metodo que consulta el valor total de una facuta...
	public String calculaTotal(String codFactura){
	try{
		String total = "";
		String queryString = "select sum(dtf.dtfValor) from DetalleFactura dtf, Factura f where dtf.factura.facCodigo = f.facCodigo and f.facCodigo=:codigo";
        Query queryObject = getSession().createQuery(queryString);
        queryObject.setParameter("codigo", codFactura);
        total = queryObject.list().get(0)+"";
		return total;
	
	} catch (RuntimeException re) {
		throw re;
	}
	
	}
}
